<script setup>
import { ref, onMounted } from 'vue'

// 响应式状态
const newTodo = ref('')
const todos = ref([
  { id: 1, text: '学习 Vue3 基础', done: true },
  { id: 2, text: '创建一个项目', done: false },
  { id: 3, text: '学习组合式 API', done: false },
])
let nextId = 4

// 方法
function addTodo() {
  if (newTodo.value.trim()) {
    todos.value.push({
      id: nextId++,
      text: newTodo.value,
      done: false,
    })
    newTodo.value = ''
  }
}

function toggleTodo(todo) {
  todo.done = !todo.done
}

function removeTodo(id) {
  todos.value = todos.value.filter((todo) => todo.id !== id)
}

onMounted(() => {
  if (inputRef.value) {
    inputRef.value.focus()
  }
})
const inputRef = ref(null)
</script>
<template>
  <div class="todo-app">
    <h2>待办事项</h2>

    <div class="add-todo">
      <input
        ref="inputRef"
        v-model="newTodo"
        placeholder="添加新的待办事项"
        @keyup.enter="addTodo"
      />
      <button @click="addTodo">添加</button>
    </div>

    <ul class="todo-list">
      <li v-for="todo in todos" :key="todo.id" :class="{ done: todo.done }">
        <input type="checkbox" :checked="todo.done" @change="toggleTodo(todo)" />
        <span class="todo-text">{{ todo.text }}</span>
        <button @click="removeTodo(todo.id)" class="delete-btn">删除</button>
      </li>
    </ul>

    <p v-if="todos.length === 0">没有待办事项，请添加一些！</p>
  </div>
</template>
<style scoped>
.todo-app {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  font-family: sans-serif;
}

.add-todo {
  display: flex;
  margin-bottom: 20px;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}

button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.todo-list {
  list-style-type: none;
  padding: 0;
}

li {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.todo-text {
  flex: 1;
  margin: 0 10px;
}

.done .todo-text {
  text-decoration: line-through;
  color: #999;
}

.delete-btn {
  background-color: #f44336;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
}
</style>
